package br.com.carrosvale.model.persistence;

import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.List;

import org.hibernate.Criteria;
import org.hibernate.SQLQuery;
import org.hibernate.criterion.DetachedCriteria;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class BaseRepository<T> extends HibernateDaoSupport {
	
	@SuppressWarnings("unchecked")
	protected Class<T> getEntityClass(){
		ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
		
		return (Class<T>) type.getActualTypeArguments()[0];
	}

	public T load( Serializable id ){
		return getHibernateTemplate().load(getEntityClass(), id);
	}
	
	public List<T> loadAll(){
		return getHibernateTemplate().loadAll(getEntityClass());
	}
	
	protected DetachedCriteria createDetachedCriteria(){
		return DetachedCriteria.forClass(getEntityClass());
	}
	
	protected Criteria createCriteria(){
		return getSession().createCriteria(getEntityClass());
	}
	
	@SuppressWarnings("unchecked")
	protected T uniqueResult( Criteria criteria ){
		return (T) criteria.uniqueResult();
	}
	
	public void save( T entity ){
		getHibernateTemplate().save(entity);
	}
	
	public void saveOrUpdate( T entity ){
		getHibernateTemplate().saveOrUpdate(entity);
	}
	
	public void saveOrUpdateAll( List<T> entities ){
		getHibernateTemplate().saveOrUpdateAll(entities);
	}
	
	public void merge( T entity ){
		getHibernateTemplate().merge(entity);
	}
	
	public void delete( Object entity ){
		getHibernateTemplate().delete(entity);
	}
	
	public void deleteAll( List<T> entities ){
		getHibernateTemplate().deleteAll(entities);
	}
	
	public SQLQuery getSqlQuery( String sql ){
		return getSession().createSQLQuery(sql);
	}
}
